import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *
from rich import print







































def On_SelectPage_UploadMainPicture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list):
    """批量上传主图图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file']")))
        element.send_keys(picture_list_str)
    except TimeoutException:
        print(f"提示 : 没有在 [选择类目页面] 找到 [input] 上传图片控件!")





def On_SelectPage_UploadMainPicture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str):
    """批量上传主图图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
            print(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@type='file']")))
        element.send_keys(picture_list_str)
    except TimeoutException:
        print(f"提示 : 没有在 [选择类目页面] 找到 [input] 上传图片控件!")














        






        




def On_InputPage_InputBasicParameters(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,AttributeName:str,AttributeValue:str,Delay:float=0.5):
    """填写基础参数

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
    """

    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./div[@attr-field-id='{AttributeName}']  and //input[not(@type='file')]]//input[not(@type='file')]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        element.send_keys(AttributeValue)
        try:
            element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@title='{AttributeValue}']/div[text()='{AttributeValue}'] | //span[@title='{AttributeValue}']/span[text()='{AttributeValue}']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            finally:
                time.sleep(Delay)
                return
        except TimeoutException:
            print(f"提示 : 没有出现想要的属性值!")
    except TimeoutException:
            print(f"提示 : 没有找到该属性!无法进行一个填写!即将对属性进行一个新建填写!")
            time.sleep(Delay)
            return
    
    # 创建属性值
    # 点击 新建按钮
    try:
        print(f"提示 : 正在尝试进行新建属性值!")
        element_xpath_value = f"//div[contains(@style,'position: absolute')]/div/div[contains(@class,'select') and not(contains(@class,'hidden'))]//span[contains(@class,'newSKU')]/span"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,element_xpath_value)))    
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [新建] 按钮!请检查!")
    
    # 输入 属性值
    try:
        element_xpath_value = f"//div[contains(@style,'position: absolute')]/div/div[contains(@class,'select') and not(contains(@class,'hidden'))]//input[@type='text']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,element_xpath_value)))
        element.send_keys(AttributeValue)
    except TimeoutException:
        print(f"提示 : 没有找到 [新建属性值输入框]!请检查!")
    
    # 确认 输入
    try:
        element_xpath_value = f"//div[contains(@style,'position: absolute')]/div/div[contains(@class,'select') and not(contains(@class,'hidden'))]//span[@alt='确认']"
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,element_xpath_value)))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [确认] 按钮!请检查!")
        




def On_InputPage_UploadMain_1b1_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@attr-field-id='主图']//input[@type='file' and @ multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图' and not(@class)]"))
        element.send_keys(picture_list_str)
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到主图1:1上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_1b1_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@attr-field-id='主图']//input[@type='file' and @ multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图' and not(@class)]"))
        element.send_keys(picture_list_str)
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到主图1:1上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_3b4_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@attr-field-id='主图3:4']//input[@type='file' and @ multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图' and not(@class)]"))
        element.send_keys(picture_list_str)
        time.sleep(Delay)
        
        # 判断是否需要裁剪图片
        try:
            element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@class='ecom-g-drawer-content' and .//*[text()='AI智能做主图'] and .//*[text()='上传']]//*[text()='上传']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            time.sleep(Delay)
        except TimeoutException:
            print("提示 : 没有找到 [图片裁剪] 按钮!")
            
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到主图3:4上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_3b4_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传主图 1:1 图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@attr-field-id='主图3:4']//input[@type='file' and @ multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图' and not(@class)]"))
        element.send_keys(picture_list_str)
        time.sleep(Delay)
        
        # 判断是否需要裁剪图片
        try:
            element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@class='ecom-g-drawer-content' and .//*[text()='AI智能做主图'] and .//*[text()='上传']]//*[text()='上传']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            time.sleep(Delay)
        except TimeoutException:
            print("提示 : 没有找到 [图片裁剪] 按钮!")
        
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到主图3:4上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadDetail_Picture_ByPictureNameList(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_name_list:list,Delay:float=5):
    """批量上传详情页图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./div/div[text()='详情编辑'] and .//input[@type='file']]//input[@type='file' and @multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//div[text()='详情编辑']"))
        element.send_keys(picture_list_str)
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到详情图上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadDetail_Picture_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,picture_directory_path:str,Delay:float=5):
    """批量上传详情页图片

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        picture_name (list): 图片名称列表
    """
    # 1.获取图片列表
    picture_name_list = list()
    for root,dirs,files in os.walk(picture_directory_path):
        for file in files:
            picture_image_path = os.path.join(root,file)
            picture_name_list.append(picture_image_path)
    
    
    # 1.将图片列表转换为 Selenium 可以使用的格式
    picture_list_str = ""
    for index, picture_name in enumerate(picture_name_list):
        picture_path = str(pathlib.Path(picture_name).absolute().resolve())
        if index > 0:  # 不是第一个元素时才添加换行符
            picture_list_str += "\n"
        picture_list_str += picture_path
    print(picture_list_str)


    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./div/div[text()='详情编辑'] and .//input[@type='file']]//input[@type='file' and @multiple]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//div[text()='详情编辑']"))
        element.send_keys(picture_list_str)
    except (NoSuchElementException,TimeoutException):
        print(f"提示 : 没有找到详情图上传图片的 [input] 控件元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_Video_ByStr(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,VideoPath:str,Delay:float=5):
    """上传主图视频

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        video_directory_path: 主图视频所在目录
    """
    # 1.获取 主图视频 路径
    VideoPath = pathlib.Path(VideoPath).absolute().resolve().__str__()
    print(f"提示 : 主图视频路径 : {VideoPath}")
            
    # 2.上传主图视频
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//label[./div[text()='主图视频'] and .//input[@type='file' and @accept='.mp4']]//input[@type='file' and @accept='.mp4']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图视频']"))
        element.send_keys(VideoPath)
    except TimeoutException:
        print(f"提示 : 没有找到上传 [主图视频] 的 [input] 控件!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadMain_Video_ByDirectory(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,video_directory_path:str,Delay:float=5):
    """上传主图视频

    Args:
        driver (WebDriver): driver 实例
        wait (WebDriverWait): WebDriverWait 实例
        actions (ActionChains): ActionChains 实例
        video_directory_path: 主图视频所在目录
    """
    # 1.获取 主图视频 路径
    video_path = str()
    for root,dirs,files in os.walk(video_directory_path):
        for file in files:
            if file.endswith(".mp4"):
                video_path = pathlib.Path(os.path.join(root,file)).absolute().resolve().__str__()
                break
            
    # 2.上传主图视频
    print(video_path)
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//label[./div[text()='主图视频'] and .//input[@type='file' and @accept='.mp4']]//input[@type='file' and @accept='.mp4']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",driver.find_element(by=By.XPATH,value="//span[text()='主图视频']"))
        element.send_keys(video_path)
    except TimeoutException:
        print(f"提示 : 没有找到上传 [主图视频] 的 [input] 控件!")
    finally:
        time.sleep(Delay)





def On_InputPage_UploadSkuPicture_And_SetSkuName(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,SkuName:str,Picture_Name:str=None,Delay:float=2):
    
    # 1.填写颜色
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./span[text()='请选择/输入颜色分类'] and .//input]//input")))
        element.send_keys(SkuName)
        
        try:
            wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//li//span[text()='{SkuName}']")))
        except TimeoutException:
            print(f"提示 : 没有等待输入 [颜色] 后的结果!")
        
    except TimeoutException:
        print("提示 : 没有找到 [颜色] 的 [input] 控件!")
    
    
    try:
        # 实现 选择颜色的逻辑
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//li//span[text()='{SkuName}']")))
        try:
            element.click()
            try:
                element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[contains(@style,'position') and contains(@style,'absolute')]//button/span[contains(text(),'确定')]")))
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
    except TimeoutException:
        print("提示 : 没有找到 [目标颜色] !")

    # 2.上传颜色图片
    # 
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@id='skuValue-颜色分类']/div[not(contains(@class,'skuValueInput')) and .//span[text()='{SkuName}']]//input[@type='file' and not(@multiple)]")))
        element.send_keys(pathlib.Path(Picture_Name).absolute().resolve().__str__())
        time.sleep(Delay)
        
        # 判断是否需要裁剪图片
        try:
            element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[./div/*[text()='图片裁剪'] and .//span[text()='确定']]//span[text()='确定']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)
            time.sleep(Delay)
        except TimeoutException:
            print("提示 : 没有找到 [图片裁剪] 按钮!")
            
    except TimeoutException:
        print(f"提示 : 没有找到 [{SkuName}] 对应的图片上传元素!")
    finally:
        time.sleep(Delay)





def On_InputPage_SelectSizeChat(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,SizeCharType:str,SizeCharList:list):
    """选择尺码类型以及尺码

    Args:
        driver (WebDriver): _description_
        wait (WebDriverWait): _description_
        actions (ActionChains): _description_
        SizeCharType (str): 尺码类型
        SizeCharList (list): 尺码列表
    """
    # 1.打开尺码表选择框
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//div[@id='skuValue-尺码大小']//input")))
        try:
            element.click()
            try:
                element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//ul/li[@title='{SizeCharType}']/span[text()='{SizeCharType}']")))
                element.click()
            except:
                print(f"提示 : 打开 [尺码表] 选择框失败!")
            
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)            
    except TimeoutException:
        print(f"提示 : 没有找到选择 [尺码表] 输入框!")

    # 2.选择尺码
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//ul/li[contains(@class,'active') and @title='{SizeCharType}']/span[text()='{SizeCharType}']"))) 
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)        
    except TimeoutException:
        print(f"提示 : 没有找到选择 [尺码类型] 的选项!")
    
    
    # 3.选择尺码列表
    for sizechar in SizeCharList:
        try:
            element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//ul/li[@title='{sizechar}']/span[text()='{sizechar}']")))
            try:
                element.click()
            except (ElementClickInterceptedException,ElementNotInteractableException):
                driver.execute_script("arguments[0].click();",element)        
        except TimeoutException:
            print(f"提示 : 没有找打 {sizechar} 尺码,不做选择!直接跳过当前尺码!")


    # 4.确认尺码返回
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//button[not(@disabled)]/span[contains(text(),'确定')]")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [确定] 按钮!")





def On_InputPage_Input_Batch_Price_And_Code(driver:WebDriver,wait:WebDriverWait,actions:ActionChains,Number:int,Price:float,Product_Code):
    """批量设置价格.
    """
    
    # 1.输入价格
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//input[@placeholder='价格']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Price)
    except TimeoutException:
        print(f"提示 : 没有找到 [价格] 输入框元素!")

    # 2.输入库存
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//input[@placeholder='现货库存']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Number)
    except TimeoutException:
        print(f"提示 : 没有找到 [现货库存] 输入框元素!")
    
    # 3.输入商家编码
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//input[@placeholder='商家编码']")))
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys(Product_Code)
    except TimeoutException:
        print(f"提示 : 没有找到 [商家编码] 输入框元素!")

    # 4.批量设置
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,f"//button[not(@disabled)]/span[text()='批量设置']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [批量设置] 按钮!")





def On_InputPage_InputOhtherParameters(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    # 1.设置 48 小时发货.
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//span[text()='48小时']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [48小时发货] 的元素选项!")
    
    
    # 2.设置订单库存计数
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,"//span[text()='付款减库存']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 没有找到 [48小时发货] 的元素选项!")
    



    
def On_InputPage_InputService(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    
    # 1.展开服务与履约
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@id,'服务与履约')]//*[text()='展开更多']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print(f"提示 : 无法对 [服务与履约] 进行展开操作!\n可能是已经展开过了!")
    
    # 2.填写购买限制
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个订单最多购买')]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys("3")
    except TimeoutException:
        print(f"提示: 没有找到 [每个订单最多购买] 输入框元素!")
    
    try:
        element = wait.until(expected_conditions.visibility_of_element_located((By.XPATH,"//input[contains(@dropdownclassname,'每个用户累计可购买')]")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        while element.get_attribute("value"):
            element.send_keys(Keys.BACKSPACE*20)
        element.send_keys("3")
    except TimeoutException:
        print(f"提示: 没有找到 [每个用户累计可购买] 输入框元素!")





def On_HtmlPage_Scroll_To_Top(driver:WebDriver,wait:WebDriverWait,actions:ActionChains):
    # 滚动到页面顶部
    driver.execute_script("window.scrollTo(0, 0);")
    try:
        element = wait.until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='商品类目']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
    except TimeoutException:
        print("提示 : 没有找到锚点元素,无法滚动至 [网页顶部] !")









if __name__ == '__main__':
    # 切换工作目录到当前脚本所在目录
    os.chdir(pathlib.Path(__file__).parent.absolute().resolve().__str__())
    Modify_Time = "2025年7月28日17:25:52"
    print(f"当前【抖店】自动化脚本的版本日期是 : 【{Modify_Time}】")

    # 判断是否是否启动浏览器
    from Wrapper.Doudian.Basic import *
    from Wrapper.Doudian.Initialization import *
    CheckResul_Process = Checkout_Has_Msedge_Process()  # 检测是否有 msedge.exe 进程
    if(CheckResul_Process == False):
        Start_Debugmode_Browser()
    else:
        CheckResul_DebugModu = Checkout_Debug_Mode_Activate()   # 检测是否处于调试模式
        if(CheckResul_DebugModu == False):
            _select_execute = Custom_Message(text="当前不是调试环境\n请问是否需要关闭所有 msedge.exe 进程\n重新打开!",type=1)
            # 1.判断选择那种方式启动浏览器
            match _select_execute:
                case 1:
                    Close_All_Msedge_Process()
                    Start_Debugmode_Browser()
                case 2:
                    exit(0)
                case _:
                    exit(0)




    # 基础配置
    driver = Fast_Create_WebDriver_Wait_Action()
    Goto_CurrentActivateUrl(driver)
    ConfigData = yaml.safe_load(stream=open(file="./config.yaml",mode="r",encoding="utf-8"))['DouDian']


    
    # 选择类目
    from Wrapper.Doudian.OpenUrl import *
    from Wrapper.Doudian.Select_Category import *
    Goto_Select_Category(driver)
    On_SelectPage_Goto_OldVersion(driver)
    On_SelectPage_Select_FirstCategory(driver,ConfigData['FirstCategory'])
    On_SelectPage_Select_SecondCategory(driver,ConfigData['SecondCategory'])
    Goto_Parameter_Input(driver)

    input("提示 : 程序结束！")
    exit(0)


    # 填写参数
    for para in ConfigData['DDBasicParameters']:
        AttributeName = para[0]
        AttributeValue = para[1]
        On_InputPage_InputBasicParameters(driver,wait,actions,AttributeName,AttributeValue)




    # 上传详情图
    DetailImageDirectory = GetExistsDirectory(ConfigData['DetailDirectoryFilterList'])
    if DetailImageDirectory:
        On_InputPage_UploadDetail_Picture_ByDirectory(driver,wait,actions,DetailImageDirectory)




    # 上传视频
    MainVideoDirectory = GetExistsDirectory(ConfigData['MainVideoDirectoryFilterList'])
    if MainVideoDirectory:
        On_InputPage_UploadMain_Video_ByDirectory(driver,wait,actions,MainVideoDirectory)




    # 填写 Sku
    
    SkuImageDirectory = GetExistsDirectory(ConfigData['SkuImageDirectoryFilterList'])
    for root,dirs,files in os.walk(SkuImageDirectory):
        for file in files:
            if file.endswith(".jpeg") or file.endswith(".jpg") or file.endswith(".png"):
                skuimagepath = pathlib.Path(os.path.join(root, file)).absolute().resolve()
                basename = pathlib.Path(os.path.join(root, file)).absolute().resolve().stem
                colorname = re.sub(r'[^\u4e00-\u9fff]', '', basename)
                On_InputPage_UploadSkuPicture_And_SetSkuName(driver,wait,actions,colorname,skuimagepath)




    # 填写尺码
    On_InputPage_SelectSizeChat(driver,wait,actions,
                   ConfigData['ChartSizeType'],
                   ConfigData['ChartSizeList'])




    # 填写价格和编码
    On_InputPage_Input_Batch_Price_And_Code(driver,wait,actions,
                               ConfigData['Number'],
                               ConfigData['Price'],
                               ConfigData['Code'])




    # 填写其他参数
    On_InputPage_InputOhtherParameters(driver,wait,actions)




    # 填写服务与履约
    On_InputPage_InputService(driver,wait,actions)




    # 上传主图1:1
    MainImageDirectory = GetExistsDirectory(ConfigData['MainDirectoryFilterList'])
    if MainImageDirectory:
        On_InputPage_UploadMain_1b1_Picture_ByDirectory(driver,wait,actions,MainImageDirectory)




    # 上传主图3:4
    MainImageDirectory = GetExistsDirectory(ConfigData['MainDirectoryFilterList'])
    if MainImageDirectory:
        On_InputPage_UploadMain_3b4_Picture_ByDirectory(driver,wait,actions,MainImageDirectory)




    # 滚动到标题
    On_HtmlPage_Scroll_To_Top(driver,wait,actions)




    # 搜索同款
    Find_MainImageTitle(driver=driver,wait=wait,actions=actions,Picture_Path=pathlib.Path(MainImageDirectory).iterdir().__next__().absolute().resolve())




    # 播放声音
    winsound.Beep(frequency=450, duration=10000)  # 频率1000Hz，持续10秒




    # 结束程序
    driver.quit()